import type { FC, ReactNode } from 'react'
import React, { memo, useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Menu, MenuProps } from 'antd'

import logoImg from '@/assets/img/logo.png'
import { MenuWrapper } from '@/views/main/c-cpns/main-menu/style'
import { myShallowEqual, useMySelector } from '@/store'
import PathToIcons from '@/assets/data/path-to-icon'

interface IProps {
  children?: ReactNode
  collapsed: boolean
}

type MenuItem = Required<MenuProps>['items'][number]

function getItem(
  label?: React.ReactNode,
  key?: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: 'group'
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type
  } as MenuItem
}

function getMenuItems(menuList: any[]) {
  const items: MenuItem[] = []
  menuList.forEach((menu) => {
    const newPath = `/main${menu.path}`
    // 根据返回的path去匹配本地准备好的图标
    const key = Object.keys(PathToIcons).find((path) => path === newPath)
    let Icon: ReactNode = <div></div>
    if (key) {
      Icon = PathToIcons[key]
    }
    let rMenu
    if (menu.children?.length) {
      rMenu = getItem(
        menu.meta.title,
        newPath,
        Icon,
        getMenuItems(menu.children)
      )
    } else {
      rMenu = getItem(menu.meta.title, newPath, Icon)
    }
    items.push(rMenu)
  })
  return items
}

const MainMenu: FC<IProps> = (props) => {
  const { menuList } = useMySelector(
    (state) => ({
      menuList: state.app.menuList
    }),
    myShallowEqual
  )

  const navigate = useNavigate()
  const location = useLocation()

  const [endItems, setEndItems] = useState<MenuItem[] | undefined>([])
  const [defaultPath, setDefaultPath] = useState('')

  useEffect(() => {
    // 获取符合antd的菜单数据
    // console.log(loadEndMenuItems())
    setEndItems(loadEndMenuItems())
  }, [menuList])

  useEffect(() => {
    // 当前路由和菜单初始选中的统一
    const currentPath = location.pathname
    setDefaultPath(currentPath)
  }, [location.pathname])

  // 获取符合antd的菜单数据
  function loadEndMenuItems() {
    if (menuList.length) {
      const children = menuList
      // 后端没有首页数据，自己加在第一个位置
      const firstChild = {
        path: '/dashboard',
        meta: { title: '工作台' }
      }
      // 拷贝一份数据再操作，防止影响共有数据
      const newChildren = [firstChild, ...children]
      return getMenuItems(newChildren)
    }
  }

  // 菜单点击页面跳转
  function menuItemClick({ key }: { key: string }) {
    setDefaultPath(key)
    navigate(key)
  }

  return (
    <MenuWrapper isCollapsed={props.collapsed}>
      <h3 className="header">
        <img className="logo" src={logoImg} alt="" />
        <span className="title">题海拾贝</span>
      </h3>
      <Menu
        theme="light"
        mode="inline"
        selectedKeys={[defaultPath]}
        items={endItems}
        onClick={menuItemClick}
      />
    </MenuWrapper>
  )
}

export default memo(MainMenu)
